/**
 * 坦克大战游戏主类
 * 依赖文件：
 * - buildings.js (建筑系统)
 * - renderer.js (渲染系统)
 * - collision.js (碰撞检测)
 * - ai.js (高智能AI系统)
 * - Vector2D.js (向量数学)
 * - InputHandler.js (输入处理)
 * - ParticleSystem.js (粒子系统)
 */

class Game {
    constructor() {
        this.canvas = null;
        this.ctx = null;
        this.inputHandler = null;
        this.particleSystem = null;
        this.renderer = null;
        
        // 游戏状态
        this.gameState = 'menu';
        this.score = 0;
        this.level = 1;
        this.lives = 3;
        this.enemyCount = 10;
        
        // AI难度设置 - 直接使用最高难度
        this.aiDifficulty = 'nightmare'; // 直接设置为最高难度，不需要难度设置
        
        // 渲染设置
        this.pixelRatio = window.devicePixelRatio || 1;
        
        // 性能监控
        this.fps = 60;
        this.frameCount = 0;
        this.lastTime = 0;
        this.deltaTime = 0;
        
        // 游戏对象
        this.player = null;
        this.enemies = [];
        this.bullets = [];
        this.missiles = []; // 导弹数组
        this.buildings = [];
        this.powerUps = [];
        
        // 屏幕震动系统
        this.screenShake = {
            intensity: 0,
            duration: 0,
            currentTime: 0,
            offset: { x: 0, y: 0 }
        };
        
        // 渲染缓存数据，避免闪烁
        this.lastUIData = {
            fps: 60,
            particleCount: 0,
            enemyCount: 0,
            bulletCount: 0
        };
        
        this.aiDebugData = {
            aliveCount: 0,
            fps: 60,
            alertCounts: { green: 0, yellow: 0, red: 0 },
            coordinatingCount: 0,
            firstEnemyState: null,
            taskCount: 0
        };
        
        this.initialize();
    }

    async initialize() {
        this.setupCanvas();
        this.setupSystems();
        this.setupEventListeners();
        
        // 初始化AI工作管理器
        console.log('🚀 初始化AI工作管理器...');
        window.gameAIManager = new AIWorkManager();
        
        this.createLevel();
        this.startGameLoop();
        
        console.log('🎮 坦克大战游戏初始化完成!');
        console.log(`🤖 AI难度设置: ${this.aiDifficulty}`);
    }

    setupCanvas() {
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');
        
        this.resizeCanvas();
        
        // 优化渲染设置，避免闪烁
        this.ctx.imageSmoothingEnabled = false;
        this.canvas.style.imageRendering = 'pixelated';
        
        // 设置固定的渲染状态
        this.ctx.textBaseline = 'top';
        this.ctx.textAlign = 'left';
        this.ctx.lineCap = 'round';
        this.ctx.lineJoin = 'round';
    }

    resizeCanvas() {
        const rect = this.canvas.getBoundingClientRect();
        this.canvas.width = window.innerWidth * this.pixelRatio;
        this.canvas.height = window.innerHeight * this.pixelRatio;
        
        this.canvas.style.width = window.innerWidth + 'px';
        this.canvas.style.height = window.innerHeight + 'px';
        
        if (this.ctx) {
            this.ctx.scale(this.pixelRatio, this.pixelRatio);
            // 重新设置渲染状态
            this.ctx.imageSmoothingEnabled = false;
            this.ctx.textBaseline = 'top';
            this.ctx.textAlign = 'left';
            this.ctx.lineCap = 'round';
            this.ctx.lineJoin = 'round';
        }
    }

    setupSystems() {
        this.inputHandler = new InputHandler();
        this.particleSystem = new ParticleSystem();
        this.renderer = new GameRenderer(this.ctx);
        
        // 减少地形细节生成频率，提高性能
        this.preGenerateTerrainDetails();
        
        this.createPlayer();
        this.createEnemies();
        this.createBuildings();
    }

    preGenerateTerrainDetails() {
        this.terrainDetails = {
            noisePoints: [],
            grassSpots: [],
            darkAreas: [],
            stones: [],
            grassBlades: []
        };
        
        // 大幅减少地形细节数量以提高性能
        for (let i = 0; i < 100; i++) { // 从200减少到100
            this.terrainDetails.noisePoints.push({
                x: Math.random() * window.innerWidth,
                y: Math.random() * window.innerHeight,
                size: 1 + Math.random() * 0.5,
                color: Math.random() > 0.5 ? '#4a6b4a' : '#1a3d1a',
                opacity: 0.05 + Math.random() * 0.1 // 降低透明度
            });
        }
        
        for (let i = 0; i < 20; i++) { // 从40减少到20
            this.terrainDetails.grassSpots.push({
                x: Math.random() * window.innerWidth,
                y: Math.random() * window.innerHeight,
                size: 2 + Math.random() * 3
            });
        }
    }

    setupEventListeners() {
        window.addEventListener('resize', () => {
            this.resizeCanvas();
        });
        
        document.addEventListener('visibilitychange', () => {
            if (document.hidden) {
                this.pause();
            }
        });
    }

    createPlayer() {
        this.player = {
            position: new Vector2D(window.innerWidth / 2, window.innerHeight / 2),
            size: new Vector2D(40, 40),
            angle: 0,
            speed: 150,
            health: 100,
            color: '#00ff88',
            lastShot: 0,
            shootCooldown: 250,
            recoilOffset: 0,
            recoilIntensity: 0,
            recoilDuration: 0,
            recoilCurrentTime: 0,
            // 导弹系统
            missiles: 10, // 导弹数量
            maxMissiles: 10,
            lastMissile: 0,
            missileCooldown: 1500 // 导弹冷却时间1.5秒
        };
    }

    createEnemies() {
        this.enemies = [];
        const enemyCount = 5; // 固定设置为5个敌方坦克
        
        console.log(`🤖 创建 ${enemyCount} 个高智能AI敌人 (难度: ${this.aiDifficulty})`);
        
        // 预定义5个分散的初始位置，避免重叠
        const spawnPositions = [
            new Vector2D(window.innerWidth * 0.2, window.innerHeight * 0.2),   // 左上
            new Vector2D(window.innerWidth * 0.8, window.innerHeight * 0.2),   // 右上
            new Vector2D(window.innerWidth * 0.2, window.innerHeight * 0.8),   // 左下
            new Vector2D(window.innerWidth * 0.8, window.innerHeight * 0.8),   // 右下
            new Vector2D(window.innerWidth * 0.9, window.innerHeight * 0.5)    // 右中
        ];
        
        for (let i = 0; i < enemyCount; i++) {
            const enemy = {
                id: `enemy_${this.level}_${i}_${Date.now()}`, // 唯一ID
                position: spawnPositions[i].clone(),
                size: new Vector2D(40, 40),
                angle: Math.random() * Math.PI * 2,
                speed: 80 + Math.random() * 40, // 不同的速度
                health: 50 + this.level * 10, // 随关卡增加血量
                color: '#ff4444',
                lastShot: 0,
                shootCooldown: 800 + Math.random() * 400, // 不同的射击频率
                moveTimer: 0,
                moveDirection: Vector2D.random(),
                isDead: false,
                recoilOffset: 0,
                recoilIntensity: 0,
                recoilDuration: 0,
                recoilCurrentTime: 0,
                // AI属性
                aiType: this.getRandomAIType(),
                difficulty: this.aiDifficulty
            };
            
            // 为每个敌人创建AI控制器
            enemy.ai = new TankAI(enemy, this.aiDifficulty);
            
            // 设置射击回调
            enemy.ai.onShoot = (angle) => {
                this.enemyShootWithAI(enemy, angle);
            };
            
            console.log(`✅ 敌人${i+1} (ID: ${enemy.id}): AI类型=${enemy.aiType}, 位置=${spawnPositions[i].x.toFixed()},${spawnPositions[i].y.toFixed()}, 血量=${enemy.health}, 速度=${enemy.speed}`);
            
            this.enemies.push(enemy);
        }
    }

    getRandomAIType() {
        const types = ['assault', 'sniper', 'flanker', 'support'];
        return types[Math.floor(Math.random() * types.length)];
    }

    createBuildings() {
        this.buildings = [];
        const tileSize = 40;
        
        console.log('🏗️ 开始创建建筑系统...');
        
        try {
            // 首先确保创建边界墙
            this.createBoundary(tileSize);
            console.log(`✅ 边界墙创建完成，当前建筑数: ${this.buildings.length}`);
            
            // 创建地形
            this.createTerrain(tileSize);
            console.log('✅ 地形创建完成');
            
            // 创建房屋
            const beforeHouses = this.buildings.length;
            this.createHouses(tileSize);
            const afterHouses = this.buildings.length;
            console.log(`✅ 房屋生成完成，新增建筑: ${afterHouses - beforeHouses}座`);
            
            console.log(`🏘️ 建筑系统创建完成! 总建筑数: ${this.buildings.length}`);
            
        } catch (error) {
            console.error('❌ 建筑系统创建失败:', error);
            
            // 确保至少有边界墙
            if (this.buildings.length === 0) {
                console.warn('🚨 完全没有建筑，强制创建边界墙');
                this.createEmergencyBoundary(tileSize);
            }
        }
        
        // 最终检查
        if (this.buildings.length === 0) {
            console.error('🚨 检测到零建筑，强制创建最小边界');
            this.createMinimalBoundary(tileSize);
        }
        
        console.log(`🎯 最终建筑统计: ${this.buildings.length}座建筑`);
    }

    createBoundary(tileSize) {
        // 边界墙 - 确保总是存在
        for (let x = 0; x < window.innerWidth; x += tileSize) {
            this.buildings.push({ 
                position: new Vector2D(x, 0), 
                size: new Vector2D(tileSize, tileSize), 
                type: 'steel',
                variant: 'boundary'
            });
            this.buildings.push({ 
                position: new Vector2D(x, window.innerHeight - tileSize), 
                size: new Vector2D(tileSize, tileSize), 
                type: 'steel',
                variant: 'boundary'
            });
        }
        
        for (let y = 0; y < window.innerHeight; y += tileSize) {
            this.buildings.push({ 
                position: new Vector2D(0, y), 
                size: new Vector2D(tileSize, tileSize), 
                type: 'steel',
                variant: 'boundary'
            });
            this.buildings.push({ 
                position: new Vector2D(window.innerWidth - tileSize, y), 
                size: new Vector2D(tileSize, tileSize), 
                type: 'steel',
                variant: 'boundary'
            });
        }
    }

    createTerrain(tileSize) {
        this.terrain = [];
        const cols = Math.ceil(window.innerWidth / tileSize);
        const rows = Math.ceil(window.innerHeight / tileSize);
        
        for (let x = 0; x < cols; x++) {
            this.terrain[x] = [];
            for (let y = 0; y < rows; y++) {
                this.terrain[x][y] = {
                    type: 'grass',
                    position: new Vector2D(x * tileSize, y * tileSize),
                    size: new Vector2D(tileSize, tileSize)
                };
            }
        }
    }

    createHouses(tileSize) {
        // 90%概率生成郊区布局（少建筑），10%概率生成密集住宅区
        const mapType = Math.random();
        
        if (mapType < 0.1) {
            this.createResidentialDistrict(tileSize);
        } else {
            this.createSuburbanLayout(tileSize);
        }
        
        console.log(`🏘️ 房屋类型: ${mapType < 0.1 ? '密集住宅区' : '郊区布局'}`);
    }

    createSuburbanLayout(tileSize) {
        // 生成 2-4 座房屋，减少建筑数量
        const houseCount = 2 + Math.floor(Math.random() * 3);
        
        console.log(`🏠 生成郊区房屋: ${houseCount}座`);
        
        for (let i = 0; i < houseCount; i++) {
            let x, y, width, height;
            let attempts = 0;
            
            do {
                width = (2 + Math.floor(Math.random() * 2)) * tileSize; // 80-120px
                height = (2 + Math.floor(Math.random() * 2)) * tileSize; // 80-120px
                
                x = tileSize * 4 + Math.random() * (window.innerWidth - width - tileSize * 8);
                y = tileSize * 4 + Math.random() * (window.innerHeight - height - tileSize * 8);
                
                attempts++;
            } while (this.isHousePositionBlocked(x, y, width, height) && attempts < 30);
            
            if (attempts < 30) {
                try {
                    // 80% 概率生成木屋，20% 概率生成混凝土房
                    if (Math.random() < 0.8) {
                        const house = new WoodenHouse(x, y, width, height);
                        this.buildings.push(house);
                        console.log(`✅ 木屋创建成功: ${x},${y} (${width}x${height})`);
                    } else {
                        const house = new ConcreteHouse(x, y, width, height);
                        this.buildings.push(house);
                        console.log(`✅ 混凝土房创建成功: ${x},${y} (${width}x${height})`);
                    }
                } catch (error) {
                    console.error(`❌ 房屋创建失败:`, error);
                }
            } else {
                console.warn(`⚠️ 房屋${i+1}位置生成失败，跳过`);
            }
        }
    }

    createResidentialDistrict(tileSize) {
        // 密集住宅区布局 - 减少房屋数量
        const rows = Math.floor((window.innerHeight - tileSize * 8) / (tileSize * 4));
        const cols = Math.floor((window.innerWidth - tileSize * 8) / (tileSize * 4));
        
        console.log(`🏘️ 生成密集住宅区: ${rows}x${cols}网格`);
        let houseCount = 0;
        
        for (let row = 0; row < rows; row++) {
            for (let col = 0; col < cols; col++) {
                // 30% 概率在此位置生成房屋（大幅减少）
                if (Math.random() < 0.3) {
                    const x = tileSize * 5 + col * tileSize * 4;
                    const y = tileSize * 5 + row * tileSize * 4;
                    
                    const width = (1.5 + Math.random() * 1) * tileSize; // 60-100px
                    const height = (1.5 + Math.random() * 1) * tileSize; // 60-100px
                    
                    // 避开中央区域
                    const centerX = window.innerWidth / 2;
                    const centerY = window.innerHeight / 2;
                    if (Math.abs(x + width/2 - centerX) > 200 || Math.abs(y + height/2 - centerY) > 200) {
                        try {
                            // 90% 概率生成木屋，10% 概率生成混凝土房
                            if (Math.random() < 0.9) {
                                const house = new WoodenHouse(x, y, width, height);
                                this.buildings.push(house);
                                houseCount++;
                            } else {
                                const house = new ConcreteHouse(x, y, width, height);
                                this.buildings.push(house);
                                houseCount++;
                            }
                        } catch (error) {
                            console.error(`❌ 住宅区房屋创建失败:`, error);
                        }
                    }
                }
            }
        }
        
        console.log(`✅ 密集住宅区房屋总数: ${houseCount}座`);
    }

    isHousePositionBlocked(x, y, width, height) {
        const centerX = window.innerWidth / 2;
        const centerY = window.innerHeight / 2;
        const margin = 40;
        
        // 检查是否与现有建筑冲突
        for (const building of this.buildings) {
            const dx = Math.abs((x + width/2) - (building.position.x + building.size.x/2));
            const dy = Math.abs((y + height/2) - (building.position.y + building.size.y/2));
            const minDistanceX = (width + building.size.x) / 2 + margin;
            const minDistanceY = (height + building.size.y) / 2 + margin;
            
            if (dx < minDistanceX && dy < minDistanceY) {
                return true;
            }
        }
        
        // 避免在地图中央生成（扩大中央区域，确保玩家复活空间）
        if (Math.abs(x + width/2 - centerX) < 200 && 
            Math.abs(y + height/2 - centerY) < 200) {
            return true;
        }
        
        return false;
    }

    createEmergencyBoundary(tileSize) {
        console.log('🚨 创建紧急边界墙...');
        
        for (let x = 0; x < window.innerWidth; x += tileSize) {
            this.buildings.push({ 
                position: new Vector2D(x, 0), 
                size: new Vector2D(tileSize, tileSize), 
                type: 'steel',
                variant: 'boundary'
            });
            this.buildings.push({ 
                position: new Vector2D(x, window.innerHeight - tileSize), 
                size: new Vector2D(tileSize, tileSize), 
                type: 'steel',
                variant: 'boundary'
            });
        }
        
        for (let y = 0; y < window.innerHeight; y += tileSize) {
            this.buildings.push({ 
                position: new Vector2D(0, y), 
                size: new Vector2D(tileSize, tileSize), 
                type: 'steel',
                variant: 'boundary'
            });
            this.buildings.push({ 
                position: new Vector2D(window.innerWidth - tileSize, y), 
                size: new Vector2D(tileSize, tileSize), 
                type: 'steel',
                variant: 'boundary'
            });
        }
        
        console.log('✅ 紧急边界墙创建完成');
    }

    createMinimalBoundary(tileSize) {
        console.log('🔧 创建最小边界墙...');
        
        const corners = [
            {x: 0, y: 0},
            {x: window.innerWidth - tileSize, y: 0},
            {x: 0, y: window.innerHeight - tileSize},
            {x: window.innerWidth - tileSize, y: window.innerHeight - tileSize}
        ];
        
        for (const corner of corners) {
            this.buildings.push({ 
                position: new Vector2D(corner.x, corner.y), 
                size: new Vector2D(tileSize, tileSize), 
                type: 'steel',
                variant: 'boundary'
            });
        }
        
        console.log(`✅ 最小边界墙创建完成，建筑数: ${this.buildings.length}`);
    }

    createLevel() {
        this.bullets = [];
        
        this.particleSystem.createExplosion(
            window.innerWidth / 2,
            window.innerHeight / 2,
            'spark',
            2
        );
    }

    // 游戏更新逻辑
    update(deltaTime) {
        if (this.gameState !== 'playing') return;
        
        this.updatePlayer(deltaTime);
        this.updateEnemiesWithAIOptimized(deltaTime);
        this.updateBullets(deltaTime);
        this.updateMissiles(deltaTime);
        this.updateParticlesOptimized();
        this.handleCollisions();
        this.updateScreenShake(deltaTime);
        this.updateRecoil(deltaTime);
        
        if (this.enemies.length === 0) {
            this.nextLevel();
        }
        
        this.inputHandler.update();
    }

    updatePlayer(deltaTime) {
        if (!this.player) return;
        
        const movement = this.inputHandler.getMovementVector();
        
        if (movement.magnitude() > 0) {
            const velocity = Vector2D.multiply(movement, this.player.speed * deltaTime);
            const newPosition = Vector2D.add(this.player.position, velocity);
            
            let canMove = true;
            const testPlayer = { position: newPosition, size: this.player.size };
            
            // 检查与建筑的碰撞
            for (const building of this.buildings) {
                if (CollisionSystem.checkTankBuildingCollision(testPlayer, building)) {
                    canMove = false;
                    break;
                }
            }
            
            // 检查与敌方坦克的碰撞
            if (canMove) {
                for (const enemy of this.enemies) {
                    if (!enemy.isDead && CollisionSystem.checkTankTankCollision(testPlayer, enemy)) {
                        canMove = false;
                        break;
                    }
                }
            }
            
            if (canMove) {
                this.player.position.copy(newPosition);
                this.player.angle = movement.angle() - Math.PI / 2;
                CollisionSystem.clampToScreen(this.player);
            }
        }
        
        if (this.inputHandler.isActionPressed('shoot')) {
            this.playerShoot();
        }
        
        // 导弹发射（鼠标右键或M键）
        if (this.inputHandler.isMousePressed(2) || this.inputHandler.isActionPressed('missile')) {
            this.playerShootMissile();
        }
    }

    updateEnemiesWithAIOptimized(deltaTime) {
        const aliveEnemies = this.enemies.filter(enemy => !enemy.isDead);
        
        // 使用异步AI更新，但不等待结果
        for (const enemy of aliveEnemies) {
            if (enemy.ai) {
                // 传递除自己外的所有活着的敌人作为队友
                const allies = aliveEnemies.filter(ally => ally !== enemy);
                // 异步调用，不阻塞主线程
                enemy.ai.update(this.player, allies, this.buildings, this.bullets, deltaTime).catch(error => {
                    console.warn('AI更新错误:', error);
                });
            }
            
            // 处理AI控制的移动
            if (enemy.moveDirection && enemy.moveDirection.magnitude() > 0) {
                const velocity = Vector2D.multiply(enemy.moveDirection, enemy.speed * deltaTime);
                const newPosition = Vector2D.add(enemy.position, velocity);
                
                let canMove = true;
                const margin = 40;
                
                // 检查边界
                if (newPosition.x < margin || newPosition.x > window.innerWidth - margin ||
                    newPosition.y < margin || newPosition.y > window.innerHeight - margin) {
                    canMove = false;
                }
                
                if (canMove) {
                    const testEnemy = { position: newPosition, size: enemy.size };
                    
                    // 简化碰撞检测，减少计算量
                    for (let i = 0; i < this.buildings.length; i += 2) { // 跳过一些建筑检测
                        const building = this.buildings[i];
                        if (CollisionSystem.checkTankBuildingCollision(testEnemy, building)) {
                            canMove = false;
                            break;
                        }
                    }
                    
                    // 检查与玩家坦克的碰撞
                    if (canMove && this.player) {
                        if (CollisionSystem.checkTankTankCollision(testEnemy, this.player)) {
                            canMove = false;
                        }
                    }
                    
                    // 检查与其他敌人坦克的碰撞
                    if (canMove) {
                        for (const otherEnemy of aliveEnemies) {
                            if (otherEnemy !== enemy && !otherEnemy.isDead && 
                                CollisionSystem.checkTankTankCollision(testEnemy, otherEnemy)) {
                                canMove = false;
                                break;
                            }
                        }
                    }
                }
                
                if (canMove) {
                    enemy.position.copy(newPosition);
                    // 确保坦克角度与移动方向一致
                    enemy.angle = enemy.moveDirection.angle() - Math.PI / 2;
                }
            }
        }
    }

    enemyShootWithAI(enemy, angle) {
        if (Date.now() - enemy.lastShot < enemy.shootCooldown) return;
        
        const bulletPos = new Vector2D(
            enemy.position.x + Math.cos(angle) * 30,
            enemy.position.y + Math.sin(angle) * 30
        );
        
        this.bullets.push({
            position: bulletPos,
            angle: angle,
            speed: 400,
            life: 3000,
            damage: 20 + this.level * 2, // 随关卡增加伤害
            color: '#ff4444',
            owner: 'enemy'
        });
        
        this.triggerRecoil(enemy, 5, 180);
        enemy.lastShot = Date.now();
        
        // AI射击特效
        this.particleSystem.createDirectionalBurst(bulletPos.x, bulletPos.y, angle, 'muzzleFlash');
    }

    updateBullets(deltaTime) {
        for (let i = this.bullets.length - 1; i >= 0; i--) {
            const bullet = this.bullets[i];
            
            const velocity = new Vector2D().fromAngle(bullet.angle, bullet.speed * deltaTime);
            bullet.position.add(velocity);
            
            bullet.life -= deltaTime;
            
            if (bullet.life <= 0 || CollisionSystem.isOutOfBounds(bullet.position)) {
                this.bullets.splice(i, 1);
                continue;
            }
            
            if (Math.random() < 0.1) {
                this.particleSystem.addParticle(bullet.position.x, bullet.position.y, {
                    velocity: new Vector2D(0, 0),
                    size: 1,
                    color: bullet.color,
                    life: 3,
                    gravity: 0,
                    friction: 1,
                    glow: true
                });
            }
        }
    }

    updateMissiles(deltaTime) {
        for (let i = this.missiles.length - 1; i >= 0; i--) {
            const missile = this.missiles[i];
            
            // 寻找最近的敌方坦克作为目标
            if (!missile.target || missile.target.isDead) {
                missile.target = this.findNearestEnemy(missile.position);
            }
            
            // 直接追踪目标，无视建筑物
            if (missile.target && !missile.target.isDead) {
                const targetDirection = Vector2D.subtract(missile.target.position, missile.position).normalize();
                const targetAngle = targetDirection.angle();
                let angleDiff = targetAngle - missile.angle;
                
                // 标准化角度差值
                while (angleDiff > Math.PI) angleDiff -= 2 * Math.PI;
                while (angleDiff < -Math.PI) angleDiff += 2 * Math.PI;
                
                // 转向速度
                const turnSpeed = missile.turnSpeed * deltaTime;
                if (Math.abs(angleDiff) > turnSpeed) {
                    missile.angle += Math.sign(angleDiff) * turnSpeed;
                } else {
                    missile.angle = targetAngle;
                }
            }
            
            // 更新位置
            const velocity = new Vector2D().fromAngle(missile.angle, missile.speed * deltaTime);
            missile.position.add(velocity);
            
            // 更新寿命
            missile.life -= deltaTime;
            
            // 创建烟雾轨迹
            if (Math.random() < 0.3) {
                this.particleSystem.addParticle(
                    missile.position.x + (Math.random() - 0.5) * 5,
                    missile.position.y + (Math.random() - 0.5) * 5,
                    {
                        velocity: new Vector2D().fromAngle(missile.angle + Math.PI, 20 + Math.random() * 10),
                        size: 2 + Math.random() * 2,
                        color: '#888888',
                        life: 1 + Math.random() * 2,
                        gravity: 20,
                        friction: 0.95,
                        glow: false
                    }
                );
            }
            
            // 移除过期或出界的导弹
            if (missile.life <= 0 || CollisionSystem.isOutOfBounds(missile.position)) {
                this.missiles.splice(i, 1);
            }
        }
    }

    // 寻找最近的敌方坦克
    findNearestEnemy(position) {
        let nearestEnemy = null;
        let nearestDistance = Infinity;
        
        for (const enemy of this.enemies) {
            if (enemy.isDead) continue;
            
            const distance = position.distance(enemy.position);
            if (distance < nearestDistance) {
                nearestDistance = distance;
                nearestEnemy = enemy;
            }
        }
        
        return nearestEnemy;
    }

    updateParticlesOptimized() {
        this.particleSystem.update();
        // 更严格地限制粒子数量
        this.particleSystem.limitParticleCount(100); // 从150减少到100
    }

    handleCollisions() {
        // 子弹与建筑碰撞
        for (let i = this.bullets.length - 1; i >= 0; i--) {
            const bullet = this.bullets[i];
            
            for (let j = this.buildings.length - 1; j >= 0; j--) {
                const building = this.buildings[j];
                
                if (CollisionSystem.checkBulletBuildingCollision(bullet, building)) {
                    this.particleSystem.createExplosion(bullet.position.x, bullet.position.y, 'spark', 0.5);
                    
                    if (building instanceof Building) {
                        const destroyed = building.takeDamage(bullet.damage);
                        if (destroyed) {
                            this.particleSystem.createExplosion(
                                building.position.x + building.size.x/2, 
                                building.position.y + building.size.y/2, 
                                'wallBreak', 
                                1.5
                            );
                            this.buildings.splice(j, 1);
                            this.triggerScreenShake(6, 250);
                        }
                    }
                    
                    this.bullets.splice(i, 1);
                    break;
                }
            }
        }
        
        // 子弹与敌人碰撞
        const enemiesToRemove = [];
        
        for (let i = this.bullets.length - 1; i >= 0; i--) {
            const bullet = this.bullets[i];
            if (bullet.owner === 'player') {
                for (let j = this.enemies.length - 1; j >= 0; j--) {
                    const enemy = this.enemies[j];
                    if (enemy.isDead) continue;
                    
                    if (CollisionSystem.checkBulletTankCollision(bullet, enemy)) {
                        enemy.health -= bullet.damage;
                        
                        this.particleSystem.createExplosion(bullet.position.x, bullet.position.y, 'explosion', 0.8);
                        
                        if (enemy.health <= 0 && !enemy.isDead) {
                            enemy.isDead = true;
                            this.particleSystem.createExplosion(enemy.position.x, enemy.position.y, 'tankDestroy', 1.5);
                            enemiesToRemove.push(j);
                            this.score += 100 + this.level * 20; // 随关卡增加分数
                        }
                        
                        this.bullets.splice(i, 1);
                        break;
                    }
                }
            }
        }
        
        enemiesToRemove.sort((a, b) => b - a);
        for (const index of enemiesToRemove) {
            this.enemies.splice(index, 1);
        }
        
        if (enemiesToRemove.length > 0) {
            this.triggerScreenShake(8, 300);
            this.updateUI();
        }
        
        // 导弹与敌人碰撞
        for (let i = this.missiles.length - 1; i >= 0; i--) {
            const missile = this.missiles[i];
            let missileHit = false;
            
            for (let j = this.enemies.length - 1; j >= 0; j--) {
                const enemy = this.enemies[j];
                if (enemy.isDead) continue;
                
                // 检查导弹与敌方坦克的距离
                const distance = missile.position.distance(enemy.position);
                if (distance <= 30) { // 导弹接触爆炸
                    missileHit = true;
                    
                    // 大爆炸效果
                    this.particleSystem.createExplosion(
                        missile.position.x, 
                        missile.position.y, 
                        'missileExplosion', 
                        2.5
                    );
                    
                    // 范围伤害
                    for (const target of this.enemies) {
                        if (target.isDead) continue;
                        const explosionDistance = missile.position.distance(target.position);
                        if (explosionDistance <= missile.explosionRadius) {
                            // 根据距离计算伤害
                            const damageRatio = 1 - (explosionDistance / missile.explosionRadius);
                            const damage = missile.damage * damageRatio;
                            target.health -= damage;
                            
                            if (target.health <= 0 && !target.isDead) {
                                target.isDead = true;
                                this.score += 150 + this.level * 30; // 导弹击杀奖励更高
                            }
                        }
                    }
                    
                    // 强烈屏幕震动
                    this.triggerScreenShake(15, 600);
                    break;
                }
            }
            
            // 导弹移除条件：只有击中敌人时才移除
            if (missileHit) {
                this.missiles.splice(i, 1);
            }
        }
        
        // 清理死亡的敌人
        for (let i = this.enemies.length - 1; i >= 0; i--) {
            if (this.enemies[i].isDead) {
                this.enemies.splice(i, 1);
            }
        }
        
        // 敌人子弹与玩家碰撞
        for (let i = this.bullets.length - 1; i >= 0; i--) {
            const bullet = this.bullets[i];
            if (bullet.owner === 'enemy' && this.player) {
                if (CollisionSystem.checkBulletTankCollision(bullet, this.player)) {
                    this.player.health -= bullet.damage;
                    
                    this.particleSystem.createExplosion(bullet.position.x, bullet.position.y, 'explosion', 0.6);
                    
                    if (this.player.health <= 0) {
                        this.lives--;
                        this.particleSystem.createExplosion(this.player.position.x, this.player.position.y, 'tankDestroy', 2.0);
                        
                        if (this.lives <= 0) {
                            this.gameState = 'gameOver';
                            document.getElementById('gameOverMenu').classList.remove('hidden');
                            document.getElementById('finalScore').textContent = this.score;
                        } else {
                            this.player.health = 100;
                            this.player.position = new Vector2D(window.innerWidth / 2, window.innerHeight / 2);
                        }
                        this.updateUI();
                    }
                    
                    this.bullets.splice(i, 1);
                }
            }
        }
    }

    playerShoot() {
        if (!this.player || Date.now() - this.player.lastShot < this.player.shootCooldown) return;
        
        const realAngle = this.player.angle + Math.PI / 2;
        const bulletPos = new Vector2D(
            this.player.position.x + Math.cos(realAngle) * 30,
            this.player.position.y + Math.sin(realAngle) * 30
        );
        
        this.bullets.push({
            position: bulletPos,
            angle: realAngle,
            speed: 500,
            life: 2000,
            damage: 25,
            color: '#ffff00',
            owner: 'player'
        });
        
        this.particleSystem.createDirectionalBurst(bulletPos.x, bulletPos.y, realAngle, 'muzzleFlash');
        this.triggerRecoil(this.player, 6, 200);
        
        this.player.lastShot = Date.now();
    }

    // 玩家发射导弹
    playerShootMissile() {
        if (!this.player || 
            Date.now() - this.player.lastMissile < this.player.missileCooldown) {
            return;
        }
        
        const realAngle = this.player.angle + Math.PI / 2;
        const missilePos = new Vector2D(
            this.player.position.x + Math.cos(realAngle) * 35,
            this.player.position.y + Math.sin(realAngle) * 35
        );
        
        // 创建导弹
        this.missiles.push({
            position: missilePos,
            angle: realAngle,
            speed: 250, // 比子弹慢
            turnSpeed: Math.PI * 2, // 转向速度 (弧度/秒)
            life: 8000, // 8秒寿命
            damage: 80, // 高伤害
            color: '#ff6600',
            owner: 'player',
            target: null, // 将自动寻找目标
            explosionRadius: 60 // 爆炸半径
        });
        
        // 发射特效
        this.particleSystem.createExplosion(missilePos.x, missilePos.y, 'spark', 1.2);
        this.particleSystem.createDirectionalBurst(missilePos.x, missilePos.y, realAngle, 'muzzleFlash');
        
        // 更强的后坐力
        this.triggerRecoil(this.player, 10, 400);
        
        this.player.lastMissile = Date.now();
        
        console.log(`🚀 无限导弹发射!`);
    }

    triggerRecoil(tank, intensity, duration) {
        tank.recoilIntensity = intensity;
        tank.recoilDuration = duration;
        tank.recoilCurrentTime = 0;
        tank.recoilOffset = 0;
    }

    updateRecoil(deltaTime) {
        this.updateTankRecoil(this.player, deltaTime);
        
        for (const enemy of this.enemies) {
            this.updateTankRecoil(enemy, deltaTime);
        }
    }

    updateTankRecoil(tank, deltaTime) {
        if (tank.recoilIntensity > 0) {
            tank.recoilCurrentTime += deltaTime * 1000;
            
            if (tank.recoilCurrentTime >= tank.recoilDuration) {
                tank.recoilOffset = 0;
                tank.recoilIntensity = 0;
                tank.recoilDuration = 0;
                tank.recoilCurrentTime = 0;
            } else {
                const progress = tank.recoilCurrentTime / tank.recoilDuration;
                
                let recoilFactor;
                if (progress < 0.3) {
                    recoilFactor = progress / 0.3;
                } else {
                    recoilFactor = 1 - (progress - 0.3) / 0.7;
                }
                
                tank.recoilOffset = tank.recoilIntensity * recoilFactor;
            }
        }
    }

    nextLevel() {
        this.level++;
        this.enemyCount = Math.min(5 + this.level, 15);
        
        // 无限导弹模式，不需要补给
        console.log(`🎉 第${this.level}关开始! 无限导弹模式`);
        
        this.bullets = [];
        this.missiles = []; // 清除所有导弹
        this.powerUps = [];
        
        this.createEnemies();
        this.createBuildings();
        
        this.updateUI();
        console.log(`🎯 第${this.level}关开始! 敌人数量: ${this.enemies.length}`);
    }

    // 渲染系统优化
    render() {
        // 清理Canvas状态，避免前一帧的影响
        this.ctx.save();
        this.ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
        this.ctx.globalAlpha = 1;
        this.ctx.globalCompositeOperation = 'source-over';
        this.ctx.shadowBlur = 0;
        this.ctx.shadowColor = 'transparent';
        
        // 应用屏幕震动
        this.ctx.translate(this.screenShake.offset.x, this.screenShake.offset.y);
        
        // 渲染背景
        this.ctx.fillStyle = '#2d4a2d';
        this.ctx.fillRect(-this.screenShake.offset.x, -this.screenShake.offset.y, window.innerWidth, window.innerHeight);
        
        // 统一每帧渲染，避免闪烁
        this.renderer.renderSimpleGrass(this.terrainDetails);
        this.renderBuildingsOptimized();
        this.renderPlayer();
        this.renderEnemiesOptimized();
        this.renderBullets();
        this.renderMissiles();
        this.renderParticles();
        
        this.ctx.restore();
        
        // 每帧渲染UI，但减少复杂计算
        this.renderUIOptimized();
        this.renderAIDebugInfoOptimized();
    }

    renderUIOptimized() {
        // 简化UI渲染，减少复杂计算
        if (this.frameCount % 5 === 0) { // 每5帧更新一次数值
            this.lastUIData = {
                fps: this.fps,
                particleCount: this.particleSystem.getParticleCount(),
                enemyCount: this.enemies.length,
                bulletCount: this.bullets.length
            };
        }
        
        // 每帧渲染UI，但使用缓存的数据
        if (this.lastUIData) {
            this.renderer.renderUI(
                this.lastUIData.fps, 
                this.lastUIData.particleCount, 
                this.lastUIData.enemyCount, 
                this.lastUIData.bulletCount
            );
        }
    }

    renderBuildingsOptimized() {
        // 视锥剔除 - 只渲染屏幕内的建筑
        const margin = 100;
        const viewLeft = -this.screenShake.offset.x - margin;
        const viewRight = -this.screenShake.offset.x + window.innerWidth + margin;
        const viewTop = -this.screenShake.offset.y - margin;
        const viewBottom = -this.screenShake.offset.y + window.innerHeight + margin;
        
        for (let i = 0; i < this.buildings.length; i++) {
            const building = this.buildings[i];
            
            // 视锥剔除检查
            if (building.position.x + building.size.x < viewLeft || 
                building.position.x > viewRight ||
                building.position.y + building.size.y < viewTop ||
                building.position.y > viewBottom) {
                continue; // 跳过屏幕外的建筑
            }
            
            try {
                if (building instanceof Building) {
                    building.render(this.ctx);
                    
                    if (building.destructible && building.health < building.maxHealth * 0.5) {
                        this.renderer.renderBuildingHealthBar(building);
                    }
                } else {
                    this.renderer.renderSimpleBuilding(building);
                }
            } catch (error) {
                console.error(`❌ 建筑${i}渲染失败:`, error, building);
                this.buildings.splice(i, 1);
                i--;
            }
        }
    }

    renderPlayer() {
        if (!this.player) return;
        
        this.renderer.renderHealthBar(this.player.position.x, this.player.position.y, this.player.health, 100);
        this.renderer.renderSimpleTank(this.player.position.x, this.player.position.y, this.player.angle, 'player', this.player);
    }

    renderEnemiesOptimized() {
        for (const enemy of this.enemies) {
            if (!enemy.isDead) {
                // 渲染视野范围（在坦克下方）
                this.renderEnemyVision(enemy);
                
                this.renderer.renderHealthBar(enemy.position.x, enemy.position.y, enemy.health, 50 + this.level * 10);
                this.renderer.renderSimpleTank(enemy.position.x, enemy.position.y, enemy.angle, 'enemy', enemy);
                
                // 每帧渲染AI状态，避免闪烁
                this.renderAIStateIndicator(enemy);
            }
        }
    }

    renderEnemyVision(enemy) {
        if (!enemy.ai || !enemy.ai.visionInfo) return;
        
        const vision = enemy.ai.visionInfo;
        const tankPos = enemy.position;
        
        this.ctx.save();
        
        // 根据不同状态设置视野锥形的样式
        let visionColor, borderColor;
        
        if (vision.playerInView) {
            // 玩家在视野内且视线通畅 - 红色
            visionColor = 'rgba(255, 0, 0, 0.25)';
            borderColor = 'rgba(255, 0, 0, 0.5)';
        } else if (vision.isInViewDistance && vision.isInViewAngle && !vision.hasLineOfSight) {
            // 玩家在视野角度和距离内，但被建筑物遮挡 - 橙色
            visionColor = 'rgba(255, 165, 0, 0.2)';
            borderColor = 'rgba(255, 165, 0, 0.4)';
        } else {
            // 正常巡逻状态 - 黄色
            visionColor = 'rgba(255, 255, 0, 0.15)';
            borderColor = 'rgba(255, 255, 0, 0.3)';
        }
        
        this.ctx.fillStyle = visionColor;
        this.ctx.strokeStyle = borderColor;
        this.ctx.lineWidth = 1;
        
        // 绘制视野锥形
        this.ctx.beginPath();
        this.ctx.moveTo(tankPos.x, tankPos.y); // 从坦克位置开始
        
        // 计算视野锥形的两个边界点
        const halfAngle = vision.viewAngle / 2;
        const leftAngle = vision.turretAngle - halfAngle;
        const rightAngle = vision.turretAngle + halfAngle;
        
        // 左边界
        const leftEndX = tankPos.x + Math.cos(leftAngle) * vision.viewDistance;
        const leftEndY = tankPos.y + Math.sin(leftAngle) * vision.viewDistance;
        
        // 右边界  
        const rightEndX = tankPos.x + Math.cos(rightAngle) * vision.viewDistance;
        const rightEndY = tankPos.y + Math.sin(rightAngle) * vision.viewDistance;
        
        // 绘制扇形
        this.ctx.arc(tankPos.x, tankPos.y, vision.viewDistance, leftAngle, rightAngle);
        this.ctx.lineTo(tankPos.x, tankPos.y);
        this.ctx.closePath();
        
        this.ctx.fill();
        this.ctx.stroke();
        
        // 如果玩家在视野内，绘制连接线
        if (vision.playerInView && this.player) {
            this.ctx.strokeStyle = 'rgba(255, 0, 0, 0.8)';
            this.ctx.lineWidth = 2;
            this.ctx.setLineDash([2, 2]);
            
            this.ctx.beginPath();
            this.ctx.moveTo(tankPos.x, tankPos.y);
            this.ctx.lineTo(this.player.position.x, this.player.position.y);
            this.ctx.stroke();
            
            this.ctx.setLineDash([]);
            
            // 在玩家位置绘制警告标记
            this.ctx.fillStyle = 'rgba(255, 0, 0, 0.8)';
            this.ctx.strokeStyle = '#ffffff';
            this.ctx.lineWidth = 2;
            
            this.ctx.beginPath();
            this.ctx.arc(this.player.position.x, this.player.position.y - 35, 6, 0, Math.PI * 2);
            this.ctx.fill();
            this.ctx.stroke();
            
            // 感叹号
            this.ctx.fillStyle = '#ffffff';
            this.ctx.font = 'bold 10px Arial';
            this.ctx.textAlign = 'center';
            this.ctx.fillText('!', this.player.position.x, this.player.position.y - 31);
        } else if (vision.isInViewDistance && vision.isInViewAngle && !vision.hasLineOfSight && this.player) {
            // 玩家在视野内但被遮挡 - 绘制虚线表示视线被阻挡
            this.ctx.strokeStyle = 'rgba(255, 165, 0, 0.6)';
            this.ctx.lineWidth = 2;
            this.ctx.setLineDash([4, 4]);
            
            this.ctx.beginPath();
            this.ctx.moveTo(tankPos.x, tankPos.y);
            this.ctx.lineTo(this.player.position.x, this.player.position.y);
            this.ctx.stroke();
            
            this.ctx.setLineDash([]);
            
            // 在玩家位置绘制"被遮挡"标记
            this.ctx.fillStyle = 'rgba(255, 165, 0, 0.8)';
            this.ctx.strokeStyle = '#ffffff';
            this.ctx.lineWidth = 2;
            
            this.ctx.beginPath();
            this.ctx.arc(this.player.position.x, this.player.position.y - 35, 6, 0, Math.PI * 2);
            this.ctx.fill();
            this.ctx.stroke();
            
            // 眼睛被划掉的符号表示看不见
            this.ctx.strokeStyle = '#ffffff';
            this.ctx.lineWidth = 2;
            this.ctx.beginPath();
            this.ctx.moveTo(this.player.position.x - 4, this.player.position.y - 39);
            this.ctx.lineTo(this.player.position.x + 4, this.player.position.y - 31);
            this.ctx.stroke();
        }
        
        this.ctx.restore();
    }

    renderAIStateIndicator(enemy) {
        if (!enemy.ai) return;
        
        const stateTexts = {
            'patrol': '巡逻',
            'engage': '交战',
            'flank': '侧翼',
            'retreat': '撤退',
            'cover': '掩体',
            'coordinate': '协调'
        };
        
        const stateColors = {
            'patrol': '#00ff00',
            'engage': '#ff8800',
            'flank': '#ff00ff',
            'retreat': '#0088ff',
            'cover': '#888888',
            'coordinate': '#ffff00'
        };
        
        const alertColors = {
            'green': '#00ff00',
            'yellow': '#ffff00',
            'red': '#ff0000'
        };
        
        this.ctx.save();
        
        // 状态文字
        const stateText = stateTexts[enemy.ai.state] || '未知';
        const stateColor = stateColors[enemy.ai.state] || '#ffffff';
        
        // 团队警报状态
        const alertLevel = enemy.ai.communication.teamAlertLevel || 'green';
        const alertColor = alertColors[alertLevel];
        
        // 是否在接收警报
        const isReceivingAlert = enemy.ai.communication.isReceivingAlert;
        const hasConvergenceTarget = enemy.ai.communication.convergenceTarget !== null;
        
        // 设置字体
        this.ctx.font = '11px Arial, sans-serif';
        this.ctx.textAlign = 'center';
        this.ctx.textBaseline = 'middle';
        
        // 状态文字背景和文字
        const stateTextWidth = this.ctx.measureText(stateText).width;
        const padding = 3;
        const bgWidth = stateTextWidth + padding * 2;
        const bgHeight = 14;
        
        // 绘制状态背景
        this.ctx.fillStyle = 'rgba(0, 0, 0, 0.8)';
        this.ctx.fillRect(
            enemy.position.x - bgWidth / 2, 
            enemy.position.y - 50, 
            bgWidth, 
            bgHeight
        );
        
        // 绘制状态文字
        this.ctx.fillStyle = stateColor;
        this.ctx.strokeStyle = '#000000';
        this.ctx.lineWidth = 1;
        this.ctx.strokeText(stateText, enemy.position.x, enemy.position.y - 43);
        this.ctx.fillText(stateText, enemy.position.x, enemy.position.y - 43);
        
        // 警报级别指示
        if (alertLevel !== 'green' || isReceivingAlert) {
            const alertSize = 6;
            this.ctx.fillStyle = alertColor;
            this.ctx.strokeStyle = '#000000';
            this.ctx.lineWidth = 1;
            
            this.ctx.beginPath();
            this.ctx.arc(enemy.position.x - 25, enemy.position.y - 25, alertSize, 0, Math.PI * 2);
            this.ctx.fill();
            this.ctx.stroke();
            
            // 如果是高警报，添加闪烁效果
            if (alertLevel === 'red' && Math.floor(Date.now() / 200) % 2) {
                this.ctx.shadowColor = alertColor;
                this.ctx.shadowBlur = 8;
                this.ctx.beginPath();
                this.ctx.arc(enemy.position.x - 25, enemy.position.y - 25, alertSize + 2, 0, Math.PI * 2);
                this.ctx.fill();
                this.ctx.shadowBlur = 0;
            }
        }
        
        // 通讯线路指示
        if (isReceivingAlert && enemy.ai.communication.alertSource) {
            this.ctx.strokeStyle = alertColor;
            this.ctx.lineWidth = 1;
            this.ctx.setLineDash([3, 3]);
            this.ctx.globalAlpha = 0.6;
            
            this.ctx.beginPath();
            this.ctx.moveTo(enemy.position.x, enemy.position.y);
            this.ctx.lineTo(
                enemy.ai.communication.alertSource.x,
                enemy.ai.communication.alertSource.y
            );
            this.ctx.stroke();
            
            this.ctx.setLineDash([]);
            this.ctx.globalAlpha = 1;
        }
        
        // 集合目标指示
        if (hasConvergenceTarget) {
            const target = enemy.ai.communication.convergenceTarget;
            this.ctx.strokeStyle = '#ffff00';
            this.ctx.lineWidth = 2;
            this.ctx.setLineDash([5, 5]);
            this.ctx.globalAlpha = 0.7;
            
            this.ctx.beginPath();
            this.ctx.moveTo(enemy.position.x, enemy.position.y);
            this.ctx.lineTo(target.x, target.y);
            this.ctx.stroke();
            
            // 在目标位置绘制标记
            this.ctx.fillStyle = '#ffff00';
            this.ctx.strokeStyle = '#000000';
            this.ctx.lineWidth = 1;
            this.ctx.setLineDash([]);
            this.ctx.globalAlpha = 0.8;
            
            this.ctx.beginPath();
            this.ctx.arc(target.x, target.y, 8, 0, Math.PI * 2);
            this.ctx.fill();
            this.ctx.stroke();
            
            // 绘制十字标记
            this.ctx.strokeStyle = '#000000';
            this.ctx.lineWidth = 2;
            this.ctx.beginPath();
            this.ctx.moveTo(target.x - 5, target.y);
            this.ctx.lineTo(target.x + 5, target.y);
            this.ctx.moveTo(target.x, target.y - 5);
            this.ctx.lineTo(target.x, target.y + 5);
            this.ctx.stroke();
            
            this.ctx.globalAlpha = 1;
        }
        
        this.ctx.restore();
    }

    renderAIDebugInfoOptimized() {
        // 每帧渲染，但每5帧更新数据
        if (this.frameCount % 5 === 0) {
            this.updateAIDebugData();
        }
        
        // 简化调试信息，减少文字渲染
        this.ctx.save();
        this.ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
        this.ctx.fillRect(10, window.innerHeight - 120, 220, 110);
        
        this.ctx.fillStyle = '#ffffff';
        this.ctx.font = '11px monospace';
        
        if (this.aiDebugData) {
            this.ctx.fillText(`AI: ${this.aiDifficulty} | 关卡: ${this.level}`, 15, window.innerHeight - 100);
            this.ctx.fillText(`敌人: ${this.aiDebugData.aliveCount} | FPS: ${this.aiDebugData.fps}`, 15, window.innerHeight - 85);
            
            // 只显示关键信息
            this.ctx.font = '10px monospace';
            this.ctx.fillText(`协调: ${this.aiDebugData.coordinatingCount} | 警报: R${this.aiDebugData.alertCounts.red} Y${this.aiDebugData.alertCounts.yellow}`, 15, window.innerHeight - 65);
            
            // 只显示1个敌人的状态
            if (this.aiDebugData.firstEnemyState) {
                this.ctx.fillText(`状态: ${this.aiDebugData.firstEnemyState}`, 15, window.innerHeight - 50);
            }
            
            // 性能监控
            this.ctx.fillText(`Worker队列: ${this.aiDebugData.taskCount}`, 15, window.innerHeight - 35);
        }
        
        this.ctx.restore();
    }

    updateAIDebugData() {
        const aliveEnemies = this.enemies.filter(e => !e.isDead);
        const alertCounts = { green: 0, yellow: 0, red: 0 };
        let coordinatingCount = 0;
        
        aliveEnemies.forEach(enemy => {
            if (enemy.ai) {
                const alertLevel = enemy.ai.communication.teamAlertLevel;
                if (alertCounts[alertLevel] !== undefined) {
                    alertCounts[alertLevel]++;
                }
                
                if (enemy.ai.state === 'coordinate') {
                    coordinatingCount++;
                }
            }
        });
        
        this.aiDebugData = {
            aliveCount: aliveEnemies.length,
            fps: this.fps,
            alertCounts,
            coordinatingCount,
            firstEnemyState: aliveEnemies[0] && aliveEnemies[0].ai ? aliveEnemies[0].ai.state : null,
            taskCount: window.gameAIManager ? window.gameAIManager.taskQueue.length : 0
        };
    }

    renderBullets() {
        for (const bullet of this.bullets) {
            this.ctx.save();
            this.ctx.globalAlpha = bullet.life / 2000;
            this.renderer.renderAPFSDSBullet(bullet);
            this.ctx.restore();
        }
    }

    renderParticles() {
        this.particleSystem.render(this.ctx);
    }

    renderMissiles() {
        for (const missile of this.missiles) {
            this.renderer.renderMissile(missile);
        }
    }

    updateUI() {
        if (document.getElementById('playerLives')) {
            document.getElementById('playerLives').textContent = this.lives;
        }
        if (document.getElementById('playerHealth')) {
            document.getElementById('playerHealth').textContent = this.player ? this.player.health : 0;
        }
        if (document.getElementById('playerMissiles')) {
            document.getElementById('playerMissiles').textContent = '∞'; // 无限符号
        }
        if (document.getElementById('playerScore')) {
            document.getElementById('playerScore').textContent = this.score;
        }
        if (document.getElementById('currentLevel')) {
            document.getElementById('currentLevel').textContent = this.level;
        }
        if (document.getElementById('enemyCount')) {
            document.getElementById('enemyCount').textContent = this.enemies.filter(e => !e.isDead).length;
        }
    }

    // 屏幕震动系统
    triggerScreenShake(intensity, duration) {
        this.screenShake.intensity = intensity;
        this.screenShake.duration = duration;
        this.screenShake.currentTime = 0;
    }

    updateScreenShake(deltaTime) {
        if (this.screenShake.intensity > 0) {
            this.screenShake.currentTime += deltaTime * 1000;
            
            if (this.screenShake.currentTime >= this.screenShake.duration) {
                this.screenShake.intensity = 0;
                this.screenShake.offset.x = 0;
                this.screenShake.offset.y = 0;
            } else {
                const progress = this.screenShake.currentTime / this.screenShake.duration;
                const currentIntensity = this.screenShake.intensity * (1 - progress);
                
                this.screenShake.offset.x = (Math.random() - 0.5) * currentIntensity * 2;
                this.screenShake.offset.y = (Math.random() - 0.5) * currentIntensity * 2;
            }
        }
    }

    // 游戏控制方法
    async startGame() {
        this.gameState = 'playing';
        document.getElementById('mainMenu').classList.add('hidden');
        
        this.level = 1;
        this.score = 0;
        
        this.createBuildings();
        this.createPlayer();
        this.createEnemies();
        
        // 初始化AI Worker网格
        if (window.gameAIManager) {
            try {
                await window.gameAIManager.initAllGrids(
                    window.innerWidth, 
                    window.innerHeight, 
                    this.buildings.map(b => ({
                        position: { x: b.position.x, y: b.position.y },
                        size: { x: b.size.x, y: b.size.y }
                    }))
                );
                console.log('✅ AI Worker网格初始化完成');
            } catch (error) {
                console.warn('⚠️ AI Worker网格初始化失败:', error);
            }
        }
        
        this.updateUI();
        
        console.log('🎮 游戏开始 - 新地图已生成!');
        console.log(`🤖 当前AI难度: ${this.aiDifficulty}`);
    }

    pause() {
        if (this.gameState === 'playing') {
            this.gameState = 'paused';
            document.getElementById('pauseMenu').classList.remove('hidden');
        }
    }

    resume() {
        if (this.gameState === 'paused') {
            this.gameState = 'playing';
            document.getElementById('pauseMenu').classList.add('hidden');
        }
    }

    restart() {
        this.gameState = 'playing';
        this.score = 0;
        this.lives = 3;
        this.level = 1;
        
        this.createBuildings();
        this.createPlayer();
        this.createEnemies();
        this.createLevel();
        this.updateUI();
        
        document.getElementById('pauseMenu').classList.add('hidden');
        document.getElementById('gameOverMenu').classList.add('hidden');
        
        console.log('🔄 游戏重启 - 新地图已生成!');
        console.log(`🤖 当前AI难度: ${this.aiDifficulty}`);
    }

    backToMenu() {
        this.gameState = 'menu';
        document.getElementById('mainMenu').classList.remove('hidden');
        document.getElementById('pauseMenu').classList.add('hidden');
        document.getElementById('gameOverMenu').classList.add('hidden');
    }

    showSettings() {
        // 原有设置功能的占位符
        alert('设置功能开发中...');
    }

    showHighScores() {
        // 原有排行榜功能的占位符
        alert('排行榜功能开发中...');
    }

    // 游戏循环优化
    startGameLoop() {
        const gameLoop = (currentTime) => {
            this.deltaTime = Math.min((currentTime - this.lastTime) / 1000, 1/30);
            this.lastTime = currentTime;
            
            this.frameCount++;
            if (this.frameCount % 60 === 0) {
                this.fps = Math.round(1 / this.deltaTime);
                
                // 性能监控和自适应优化
                if (this.fps < 30) {
                    this.autoOptimizePerformance();
                }
            }
            
            this.update(this.deltaTime);
            this.render();
            
            if (this.inputHandler.isActionPressed('pause') && this.gameState === 'playing') {
                this.pause();
            } else if (this.inputHandler.isActionPressed('pause') && this.gameState === 'paused') {
                this.resume();
            }
            
            requestAnimationFrame(gameLoop);
        };
        
        requestAnimationFrame(gameLoop);
    }

    autoOptimizePerformance() {
        console.log('📊 检测到性能问题，自动优化...');
        
        // 减少粒子数量
        this.particleSystem.limitParticleCount(50);
        
        // 减少地形细节
        if (this.terrainDetails.noisePoints.length > 50) {
            this.terrainDetails.noisePoints = this.terrainDetails.noisePoints.slice(0, 50);
        }
        
        // 减少草地斑点
        if (this.terrainDetails.grassSpots.length > 10) {
            this.terrainDetails.grassSpots = this.terrainDetails.grassSpots.slice(0, 10);
        }
        
        console.log('✅ 性能优化完成');
    }

    // 清理资源
    destroy() {
        if (window.gameAIManager) {
            window.gameAIManager.destroy();
            window.gameAIManager = null;
        }
    }
} 